package com.macro.mall.tiny.modules.foster.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.foster.model.User;
import com.macro.mall.tiny.modules.foster.model.UserRole;
import com.macro.mall.tiny.modules.foster.model.UserRoleRelation;
import com.macro.mall.tiny.modules.foster.model.dto.AuthCodeDTO;
import com.macro.mall.tiny.modules.foster.model.dto.LoginDTO;
import com.macro.mall.tiny.modules.foster.model.vo.LoginVO;
import com.macro.mall.tiny.modules.foster.service.UserRoleRelationService;
import com.macro.mall.tiny.modules.foster.service.UserRoleService;
import com.macro.mall.tiny.modules.foster.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhuyi
 * @since 2024-03-26
 */

@Api(tags = "UserController", description = "用户管理")
@RestController
@RequestMapping("/foster/user")
@CrossOrigin
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleRelationService userRoleRelationService;
    @Autowired
    private UserRoleService userRoleService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    /**
     * 分页查询用户列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("分页查询用户列表")
    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<User>> list(@RequestParam(value = "pageNum", defaultValue = "1")
                                                    @ApiParam("页码") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5")
                                                    @ApiParam("每页数量") Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        //不能查出管理员用户
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .eq("is_admin",0);
        Page<User> pageResult = userService.page(page,wrapper);
        LOGGER.info("用户列表查询状态：查询成功");
        return CommonResult.success(CommonPage.restPage(pageResult));
    }

    /**
     * 获取指定id的用户
     * @param id
     * @return
     */
    @ApiOperation("获取指定id的用户")
    @RequestMapping(value = "/getUserById/{id}", method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('user','admin')")
    public CommonResult<User> getUserById(@PathVariable("id") Long id) {
        CommonResult commonResult = userService.getUserById(id);
        return commonResult;
    }

    /**
     * 删除指定id的用户
     * @param id
     * @return
     */
    @ApiOperation("删除指定id的用户")
    @RequestMapping(value = "/deleteUserById/{id}", method = RequestMethod.DELETE)
    @PreAuthorize("hasAuthority('admin')")
    public CommonResult deleteUserById(@PathVariable("id") Long id) {
        CommonResult commonResult = userService.removeUserById(id);
        return commonResult;
    }

    /**
     * 更新指定id用户信息
     * @param user
     * @return
     */
    @ApiOperation("更新指定id用户信息")
    @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
    @PreAuthorize("hasAnyAuthority('user','admin')")
    public CommonResult updateUser(@RequestBody User user) {
        CommonResult commonResult = userService.updateUserById(user);
        return commonResult;
    }

    /**
     * 忘记密码
     * @param loginDTO
     * @return
     */
    @ApiOperation("忘记密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public CommonResult updateBrand(@RequestBody LoginDTO loginDTO) {
        CommonResult commonResult = userService.updatePassword(loginDTO);
        return commonResult;
    }

    /**
     * 登录以后返回token
     * @param loginDTO
     * @return
     */
    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult login(@RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        LoginVO loginVO = new LoginVO();
        String username = loginDTO.getUsername();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .eq("username",username);
        User user = userService.getOne(wrapper);
        QueryWrapper<UserRoleRelation> authWrapper = new QueryWrapper<>();
        authWrapper
                .eq("user_id",user.getId());
        UserRoleRelation userRoleRelation = userRoleRelationService.getOne(authWrapper);
        QueryWrapper<UserRole> roleWrapper = new QueryWrapper<>();
        //获取角色权限
        roleWrapper
                .eq("id",userRoleRelation.getRoleId());
        UserRole userRole = userRoleService.getOne(roleWrapper);
        //判断权限
        if (userRole.getName().equals("admin")) {
            loginVO.setIsAdmin(1);
        }else loginVO.setIsAdmin(0);
        loginVO.setToken(token);
        loginVO.setTokenHead(tokenHead);
        loginVO.setUserId(user.getId());
        loginVO.setNickName(user.getNickName());
        return CommonResult.success(loginVO);
    }

    /**
     * 校验验证码
     * @param authCodeDTO
     * @return
     */
    @ApiOperation(value = "校验验证码")
    @RequestMapping(value = "/checkAuthCode", method = RequestMethod.POST)
    public CommonResult checkAuthCode(@RequestBody AuthCodeDTO authCodeDTO) {
        CommonResult commonResult = userService.checkAuthCode(authCodeDTO);
        return commonResult;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @ApiOperation(value = "注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public CommonResult register(@RequestBody User user) {
        CommonResult commonResult = userService.register(user);
        return commonResult;
    }
}
